package cn.guetzjb.security.aspect;

import cn.guetzjb.security.anotation.RequiresPermissions;
import cn.guetzjb.security.anotation.RequiresRoles;
import cn.guetzjb.security.utils.AuthUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class PreAuthorizeAspect {


    @Pointcut("@annotation(cn.guetzjb.security.anotation.RequiresPermissions) ||" +
            "@annotation(cn.guetzjb.security.anotation.RequiresRoles)")
    public void pointcut() {
    }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        RequiresPermissions annotation = signature.getMethod().getAnnotation(RequiresPermissions.class);
        //校验权限
        if (annotation != null) {
            AuthUtil.checkPermission(annotation);
        }
        RequiresRoles requiresRoles = signature.getMethod().getAnnotation(RequiresRoles.class);
        //校验角色
        if (requiresRoles != null) {
            AuthUtil.checkRole(requiresRoles);
        }
        return joinPoint.proceed();
    }
}
